package com.manor.main.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.Response;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.AbsActivity;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.dialog.XVerifyPopup;
import com.manor.common.event.LoginSuccessEvent;
import com.manor.common.http.JHttpCallback;
import com.manor.common.http.JJsonBean;
import com.manor.common.utils.ActivityManager;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.DataCleanManager;
import com.manor.common.utils.GsonUtil;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.SpUtils;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.im.utils.PushUtils;
import com.manor.main.R;
import com.manor.main.bean.LoginBean;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpConsts;
import com.manor.main.personalcenter.PersonalSettingsActivity;
import com.manor.main.utils.CodeTimeCount;
import com.mob.adsdk.AdSdk;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;

/**
 * 手机验证码登录
 */
public class VCodeVerifyFragment extends Fragment implements View.OnClickListener {

    public static final String REGEX_PHONE = "^[0-9]{11}$";
    private Context mContext;
    private CodeTimeCount codeTimeCount;
    private boolean mFirstLogin;//是否是第一次登录.
    /**
     * 0:忘记密码
     * 1:注册
     */
    public static final String FLAG_FROM_TYPE = "fromType";
    public static final String FLAG_TITLE_TEXT = "title";
    public static final String FLAG_BTN_TEXT = "btnText";
    public static final String FLAG_INPUT_HINT = "inputHint";
    public static final String FLAG_PHONE = "flagPhone";
    private int fromType;//0 登录， 1 注册， 3 重置密码
    private String titleText;
    private String btnText;
    private String inputHint;
    private EditText etPassword, etConfirmPassword;
    private EditText etPhoneNumber;
    private EditText etVCode;
    private EditText etInvite;
    private Button btnLogin;
    private String riskToken;

    private String mPhoneText;


    public VCodeVerifyFragment() {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    public static VCodeVerifyFragment newInstance() {
        return new VCodeVerifyFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            fromType = arguments.getInt(FLAG_FROM_TYPE);
            titleText = arguments.getString(FLAG_TITLE_TEXT);
            btnText = arguments.getString(FLAG_BTN_TEXT);
            inputHint = arguments.getString(FLAG_INPUT_HINT);
            mPhoneText = arguments.getString(FLAG_PHONE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sms_register, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        etPhoneNumber = view.findViewById(R.id.et_phone_number);
        etVCode = view.findViewById(R.id.et_code);


        TextView tvVcode = view.findViewById(R.id.tv_vcode);
        etPassword = view.findViewById(R.id.et_password);
        etConfirmPassword = view.findViewById(R.id.et_confirm_password);
        btnLogin = view.findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        tvVcode.setOnClickListener(this);
        codeTimeCount = new CodeTimeCount(59000, 1000, tvVcode);

        TextView tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText(titleText);
        btnLogin.setText(btnText);

        etInvite = view.findViewById(R.id.ed_invite_code);
        view.findViewById(R.id.tv_getcode).setOnClickListener(this);

        Toolbar toolbar = view.findViewById(R.id.toolbar);

        if (mContext instanceof AbsActivity) {
            ((AbsActivity) mContext).setSupportActionBar(toolbar);
            ((AbsActivity) mContext).getSupportActionBar().setDisplayShowTitleEnabled(false);
            ((AbsActivity) mContext).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
                        KeyboardUtils.hideSoftInput((AbsActivity) mContext);
                    }
                    ((AbsActivity) mContext).onBackPressed();
                }
            });
        }

        if (fromType == 1) {
            view.findViewById(R.id.rlInvite).setVisibility(View.VISIBLE);
        } else {
            view.findViewById(R.id.rlInvite).setVisibility(View.GONE);
        }

        if (fromType == 3) {
            if (!TextUtils.isEmpty(mPhoneText)) {
                etPhoneNumber.setEnabled(false);
                etPhoneNumber.setText(mPhoneText);
            } else {
                etPhoneNumber.setEnabled(true);
            }
        }
    }


    private void verifyCode(String phoneNum, String vCode, String password, String inviteCode) {
        if (mContext instanceof LoginActivity) {
            ((LoginActivity) mContext).showWaitingDialog(false);
        }
        // 忘记密码
        if (fromType == 0) {
            forgetPassword(fromType, phoneNum, vCode, password);
        } else if (fromType == 1) { // 注册
            register(phoneNum, vCode, password, inviteCode);
        } else if (fromType == 3) { //重置密码
            forgetPassword(fromType, phoneNum, vCode, password);
            // resetPassword(fromType, phoneNum, vCode, password);
        }
    }

    /**
     * 账号密码注册
     */
    private void register(String phoneNum, String vCode, String password, String inviteCode) {
        if (getActivity() instanceof LoginActivity) {
            LoginActivity activity = (LoginActivity) getActivity();



            String encryptPassword = new String(EncryptUtils.encryptAES2Base64(password.getBytes(),
                    LauncherLoginFragment.AES_KEY.getBytes(),
                    LauncherLoginFragment.AES_TRANSFORM, LauncherLoginFragment.AES_IV.getBytes()));

            if (BaseLocationActivity.npcCode == 0) {
                activity.showWaitingDialog(false);
                if (sun >= 3) {
                    // ToastUtil.show("无法获取您的位置，请走到开阔地带重试");
                    activity.dismissWaitingDialog();
                    sun = 0;
                } else {
                    Message msg = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", password);
                    bundle.putString("sms", vCode);
                    bundle.putString("pswd", password);
                    bundle.putString("inviteCode", inviteCode);
                    msg.setData(bundle);
                    msg.what = 0;
                    handler.sendMessageDelayed(msg, 1000);//发送消息
                    sun++;
                    return;
                }
            } else {
                activity.dismissWaitingDialog();
            }

            activity.showWaitingDialog(false);

            JMainHttpUtil.register(phoneNum, encryptPassword, vCode, BaseLocationActivity.npcCode, inviteCode,
                    new JHttpCallback() {
                        @Override
                        public void onSuccess(int code, String msg, String info) {
                            activity.dismissWaitingDialog();
                            if (code == 200) {
                                onMsgSuccess(code, msg, info);
                                activity.goBackLogin();
                            } else {
                                ToastUtil.show(msg);
                            }
                        }

                        @Override
                        public void onError(Response<JJsonBean> response) {
                            super.onError(response);
                            activity.dismissWaitingDialog();
                            ToastUtil.show(response.getException().getMessage());
                        }
                    });
        }
    }

    private final MyHandler handler = new MyHandler(this);

    public static class MyHandler extends Handler {

        private final WeakReference<VCodeVerifyFragment> reference;

        public MyHandler(VCodeVerifyFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            VCodeVerifyFragment vCodeLoginFragment = reference.get();
            if (vCodeLoginFragment != null) {
                Bundle data = msg.getData();
                String phone = data.getString("phone");
                String sms = data.getString("sms");
                String pswd = data.getString("pswd");
                String inviteCode = data.getString("inviteCode");
                vCodeLoginFragment.register(phone, sms, pswd, inviteCode);
            }
        }
    }

    int sun = 0;

    private void onMsgSuccess(int code, String msg, String info) {
        if (code == 200 && !info.equals("")) {
            LoginBean loginBean = GsonUtil.gsonToBean(info, LoginBean.class);
            BaseLocationActivity.parentSdNo = loginBean.getParentSdNo();
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, loginBean.getUsersig());
            MobclickAgent.onProfileSignIn(Constants.MOB_PHONE, loginBean.getUid());
            EventBus.getDefault().post(new LoginSuccessEvent());
            CommonAppConfig.getInstance().setLoginInfo(loginBean.getUid(), loginBean.getAccessToken(), true);
            SpUtil.getInstance().setStringValue(SpUtil.JAVA_TOKEN,
                    loginBean.getTokenType() + " " + loginBean.getAccessToken());
            ToastUtil.show("注册成功，请登录");
        } else {
            ToastUtil.show(msg);
        }
    }

    /**
     * 重置密码
     *
     * @param fromType
     * @param phoneNum
     * @param vCode
     * @param password
     */
    private void resetPassword(int fromType, String phoneNum, String vCode, String password) {

        // 1.登出
        logout();
        // 2.跳转到登录界面
        ActivityManager.getInstance().finishOtherActivities(PersonalSettingsActivity.class, false);
        ARouter.getInstance().build(RouteUtil.PATH_LAUNCHER)
                .navigation();
    }


    /**
     * 退出登录
     */
    private void logout() {
        SpUtils.getInstance(mContext).clear();
        SpUtil.getInstance().clear();
        CommonAppConfig.getInstance().clearLoginInfo();
        DataCleanManager.clearAllCache(mContext);
        //退出IM
        TUIKit.unInit();
        TUIKit.logout(new IUIKitCallBack() {
            @Override
            public void onSuccess(Object data) {
                TUIKit.unInit();
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {

            }
        });
        PushUtils.deleteToken(mContext);
        //友盟统计登出
        MobclickAgent.onProfileSignOff();
        AdSdk.getInstance().setUserId(null);


    }

    /**
     * 忘記密码 成功后回到密码登录界面
     *
     * @param fromType
     * @param phoneNum
     * @param vCode
     * @param password
     */
    public void forgetPassword(int fromType, String phoneNum, String vCode, String password) {
        if (getActivity() instanceof LoginActivity) {
            String encryptPassword = new String(EncryptUtils.encryptAES2Base64(password.getBytes(),
                    LauncherLoginFragment.AES_KEY.getBytes(),
                    LauncherLoginFragment.AES_TRANSFORM, LauncherLoginFragment.AES_IV.getBytes()));
            JMainHttpUtil.resetPassword(phoneNum, encryptPassword, vCode, new JHttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String info) {
                    ((LoginActivity) getActivity()).dismissWaitingDialog();
                    if (code == 200) {
                        if (fromType == 3) {
                            logout();
                            ActivityManager.getInstance().finishOtherActivities(PersonalSettingsActivity.class, false);
                            ARouter.getInstance().build(RouteUtil.PATH_LAUNCHER)
                                    .navigation();
                        } else {
                            ToastUtil.show(msg);
                            ((LoginActivity) getActivity()).goBackLogin();
                        }
                    } else {
                        ToastUtil.show(msg);
                    }
                }

                @Override
                public void onError(Response<JJsonBean> response) {
                    ((LoginActivity) getActivity()).dismissWaitingDialog();
                    super.onError(response);
                    ToastUtil.show(response.getException().getMessage());
                }
            });
        }

    }


    /**
     * 验证手机号
     */
    private boolean verifyPhone(String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show("手机号码不能为空");
            return true;
        }
        if (!RegexUtils.isMatch(REGEX_PHONE, phoneNum)) {
            ToastUtil.show("手机号码格式不正确");
            return true;
        }
        return false;
    }


    private void doSmsMsg(String phone) {
        JMainHttpUtil.getIsWY(new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 200) {
                    if ("true".equals(info) && StringUtil.isEmpty(riskToken)) {
                        XVerifyPopup.Companion.load(getActivity(), new SimpleCallback(), new Function2<Boolean,
                                String, Unit>() {
                            @Override
                            public Unit invoke(Boolean boo, String s) {
                                if (boo) {
                                    riskToken = s;
                                    sendMsgCode(phone);
                                }
                                return null;
                            }
                        });
                    } else {
                        sendMsgCode(phone);
                    }
                }
            }
        });
    }


    /**
     * 发送验证码
     */
    private void sendMsgCode(String phone) {

        if (mContext instanceof AbsActivity) {
            ((AbsActivity) mContext).showWaitingDialog(false);
        }
        //fromType 0 登录， 1 注册， 3 重置密码
        //
        //type 1.注册 2.短信登陆 3.忘记密码
        int type = 2;
        if (fromType == 1 || fromType == 3) {
            type = fromType;
        }


        JMainHttpUtil.getSmsCode(phone, type, riskToken, new JHttpCallback() {
            @Override
            public void onError() {
                super.onError();
                ToastUtil.show("服务器返回错误");
                if (mContext instanceof AbsActivity) {
                    ((AbsActivity) mContext).dismissWaitingDialog();
                }
            }

            @Override
            public void onSuccess(int code, String msg, String info) {
                if (mContext instanceof AbsActivity) {
                    ((AbsActivity) mContext).dismissWaitingDialog();
                }
                if (code == 200) {
                    ToastUtil.show("验证码已通过短信发送至+86 " + phone);
                    codeTimeCount.start();
                } else if (code == 1509) {
                    //验证失败，重新验证
                    riskToken = "";
                    ToastUtil.show(msg);
                }
                //                else if (code == 400) {
                //                    ToastUtil.show("验证码已发送至+86 " + phone);
                //                }
                else {
                    ToastUtil.show(msg);
//                    codeTimeCount.cancel();
//                    codeTimeCount.onFinish();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (codeTimeCount != null) {
            codeTimeCount.cancel();
            codeTimeCount.onFinish();
            codeTimeCount = null;
        }
        JMainHttpUtil.cancel(MainHttpConsts.CODE_TYPE);
        JMainHttpUtil.cancel(MainHttpConsts.RESET_PASSWORD);
    }

    private void getInviteCode() {
        new XPopup.Builder(mContext)
                .asConfirm(null, "是否没有邀请人，确认后无法修改", "取消", "确定", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        JMainHttpUtil.getInvitationCode(new JHttpCallback() {
                            @Override
                            public void onSuccess(int code, String msg, String info) {
                                if (code != 200) {
                                    ToastUtil.show(msg);
                                    return;
                                }

                                if (code == 200) {
                                    //  StringDataBean stringDataBean = GsonUtil.gsonToBean(info,StringDataBean
                                    //  .class);
                                    etInvite.setText(info + "");
                                }
                            }

                            @Override
                            public void onError() {
                                super.onError();

                            }
                        });
                    }
                }, null, false).show();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        String phoneNum = etPhoneNumber.getText().toString().trim();
        if (ClickUtil.canClick()) {
            if (id == R.id.tv_vcode) {// 获取验证码
                if (verifyPhone(phoneNum)) {
                    return;
                }
                doSmsMsg(phoneNum);
            } else if (id == R.id.tv_getcode) {
                getInviteCode();
            } else if (id == R.id.btn_login) {// 确定
                //            验证手机号
                if (verifyPhone(phoneNum)) {
                    return;
                }

                // 验证验证码
                String vCode = etVCode.getText().toString().trim();
                if (TextUtils.isEmpty(vCode)) {
                    ToastUtil.show("请输入验证码");
                    return;
                }
                // 验证密码
                String firstPassword = "zz";
//                String firstPassword = etPassword.getText().toString().trim();
//                if (TextUtils.isEmpty(firstPassword)) {
//                    ToastUtil.show("请输入密码");
//                    return;
//                }
//                if (!RegexUtils.isMatch(LoginActivity.REGEX_PSWD, firstPassword)) {
//                    ToastUtil.show("请输入密码长度8-12位");
//                    return;
//                }
//                String secondPassword = etConfirmPassword.getText().toString().trim();
//                if (TextUtils.isEmpty(secondPassword)) {
//                    ToastUtil.show("请再次输入密码");
//                    return;
//                }
//                if (!firstPassword.equals(secondPassword)) {
//                    ToastUtil.show("密码输入不一致");
//                    return;
//                }

                String iCode = etInvite.getText().toString().trim();
                if (fromType == 1 && StringUtil.isEmpty(iCode)) {
                    ToastUtil.show("请输入邀请码");
                    return;
                }
                if (KeyboardUtils.isSoftInputVisible((AbsActivity) mContext)) {
                    KeyboardUtils.hideSoftInput((AbsActivity) mContext);
                }
                verifyCode(phoneNum, vCode, firstPassword, iCode);
            }
        }

    }
}